#include "ACUAS/ACUAS.h"
#include "ACUAS/ACUASlcd.h"

int i,c,d,p_initial,p_actual,x,y,position;


int conversion()            //fuction to convert the position in angle
{
c=y/x;
d=x-y;
if(c==1)                    //x is bigger,the angle is between 0 & 180
{
  if(d<162 && y>336)
   {
    p_actual=135-((x-502)/1.82);
   }
   else
     p_actual=((x-256)/1.82);
}
else if(c==0)              //y is bigger,the angle is between 180 & 360
   {
   if(d>-162 && x>336)
    {
	 p_actual=180+((y-420)/1.82);
    }
	else
	  p_actual=225-((y-502)/1.82);
   }
     else if(x==y && x>338)
	   {
        p_actual=180;
       }
	   else
	   {p_actual=0;
	   }

}


int calibrate()
{
if(i==0)
{
p_initial=p_actual;         //store the initial position
i=i++;
}
}



int position_xy()
{
if(i==1)
{
position=p_actual-p_initial;
LCD_XY(1,1) LCD_TEXT("                ")     //Clean 1st row
LCD_XY(1,2) LCD_TEXT("                ")     //Clean 2nd row
LCD_XY(8,2)
LCD_NUMBER(position)
}
}

void read_xy(void)          //Interrupt initialisation
{
ADMUX=0x40;                 //ADC0, Left adjust,AVCC reference voltage
ADCSRA=0xC4;                //Enable ADC, ADC interrupt, prescaler 128
loop_until_bit_is_clear(ADCSRA,ADSC);
x = ADCW;
ADMUX=0x41;                 //ADC0, Left adjust,AVCC reference voltage
ADCSRA=0xC4;                //Enable ADC, ADC interrupt, prescaler 128
loop_until_bit_is_clear(ADCSRA,ADSC);
y = ADCW;
}

PROGRAM_INIT


	DDRC = 0b11111111; // Output data direction: LEDs at Port C
	DDRA = 0b00000000;
	PORTA= 0b11111111;


PROGRAM_START

read_xy();
ON_BUTTON(4);
{
conversion();
calibrate();
}
position_xy();
ON_BUTTON(5);
{
i=0;
}

PROGRAM_END


